package com.wxq.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Map;

/**
 * @author Jim
 * @date 5:27 下午 2022/4/12
 * @description jwt工具
 * @email:huwmz04153277@126.com
 */
public class JwtUtils {

    /**
     * 私钥加密token
     * @param map
     * @param key
     * @param expireMinutes
     * @return
     * @throws Exception
     */
    public static String generateToken(Map<String,Object> map, PrivateKey key,int expireMinutes) throws Exception{
        return Jwts.builder()
                .setClaims(map)
                .setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
                .signWith(key, SignatureAlgorithm.RS256)
                .compact();
    }

    /**
     * 共要解析token
     * @param token
     * @param key
     * @return
     */
    private static Jws<Claims> parserToken(String token, PublicKey key){
        return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
    }

    /**
     * 获取token中用户信息，解析token
     * @param token
     * @param key
     * @return
     * @throws Exception
     */
    public static Map<String, Object> getInfoFromToken(String token,PublicKey key) throws Exception{
        Jws<Claims> claimsJws = parserToken(token,key);
        return claimsJws.getBody();
    }
}
